const express = require('express');
const mysql = require('mysql');
const bodyParser = require('body-parser');

const db = mysql.createConnection({
    host: 'db',
    port: 3306,
    user: 'root',
    password: '123456',
    database: 'mydb',
});

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));


app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Headers', '*');
    res.setHeader('Access-Control-Allow-Methods', '*');
    next();
});

// 查询接口
app.get('/', (req, res) => {
    db.query('select * from user', (err, results, fields) => {
        res.send(err || results);
    });
});

// 添加接口
app.post('/', (req, res) => {
    db.query(`insert into user (id,name) values (${req.body.id},'${req.body.name}')`, (err, results, fields) => {
        res.send(err || '成功');
    });
});

// 删除接口
app.delete('/:id', (req, res) => {
    db.query(`delete from user where id=${req.params.id}`, (err, results, fields) => {
        res.send(err || '成功');
    });
});

app.use((err, req, res, next) => {
    res.send(err);
});

// 启动服务
app.listen(80, () => {
    console.log('启动成功');
});
